﻿using DataProcess.Core.Model;
using System;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Threading;
using System.Windows.Forms;

namespace DataProcess
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Thread.CurrentThread.CurrentUICulture = new CultureInfo("zh-Hans");
            log4net.Config.XmlConfigurator.Configure();

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            //判断是否已经运行，防止端口冲突
            Process instance = RunningInstance();
            if (instance != null)
            {
                MessageBox.Show("您的电脑已经运行了一个程序。");
                Application.Exit();
                return;
            }

            Application.Run(new MainForm());

        }

        private static MainForm InstanceForm = null;
        private static readonly object padlock = new object();

        public static MainForm Instance
        {
            get
            {
                lock (padlock)
                {
                    if (InstanceForm == null)
                    {
                        InstanceForm = new MainForm();
                    }
                    return InstanceForm;
                }
            }
        }

        public static SystemSetting SystemSetting { get; set; }

        /// <summary>
        /// 判断是否已经运行
        /// </summary>
        /// <returns></returns>
        public static Process RunningInstance()
        {
            Process current = Process.GetCurrentProcess();
            Process[] processes = Process.GetProcessesByName(current.ProcessName);

            //遍历正在有相同名字运行的例程 
            foreach (Process process in processes)
            {
                //忽略现有的例程 
                if (process.Id != current.Id)
                {
                    //确保例程从EXE文件运行 
                    if (Assembly.GetExecutingAssembly().Location.Replace("/ ", "\\ ") == current.MainModule.FileName)
                    {
                        //返回另一个例程实例 
                        return process;
                    }
                }
            }
            //没有其它的例程，返回Null 
            return null;
        }
    }
}
